package com.neshai.webapp.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neshai.webapp.entity.User;
import com.neshai.webapp.mapper.UserMapper;
import com.neshai.webapp.utils.SignatureUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@RequiredArgsConstructor
public class AuthService {

    //private static final AtomicInteger counter = new AtomicInteger(100);

    private final UserMapper userMapper;

    private final VerificationCodeService verificationCodeService;

    public int emailAuth(String email, String code) {
        if(email == null || code == null || email.isEmpty() || code.isEmpty()) {
            return -1;
        }
        if (verificationCodeService.verifyCode(email, code)) {
            verificationCodeService.removeCode(email);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("email", email);
            List<User> users = userMapper.selectList(queryWrapper);
            if (!users.isEmpty()) {
                User user = users.getFirst();
                //TODO
                //登陆日志
                return user.getUserId();
            } else {
                User user = new User();
                user.setEmail(email);
                user.setVipLevel(0);
                user.setCreatedAt(LocalDateTime.now());
                user.setUsageBasic(0);
                user.setUsagePremium(0);
                user.setBalance(0L);
                userMapper.insert(user);
                return user.getUserId();
            }

        } else {
            return -1;
        }
    }

    public int walletAuth(String signMessage, String message, String wallet) {
        if (SignatureUtil.verifySignature(message, signMessage, wallet)) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("wallet_address", wallet);
            List<User> users = userMapper.selectList(queryWrapper);
            if (!users.isEmpty()) {
                User user = users.getFirst();
                //TODO
                //登陆日志
                return user.getUserId();
            } else {
                User user = new User();
//                user.setUserId(counter.incrementAndGet());
                user.setWalletAddress(wallet);
                user.setVipLevel(0);
                user.setCreatedAt(LocalDateTime.now());
                user.setUsageBasic(0);
                user.setUsagePremium(0);
                user.setBalance(0L);
                userMapper.insert(user);
                return user.getUserId();
            }
        } else {
            return -1;
        }
    }
}
